const express = require("express");
const router = express.Router();
const fs = require("fs");
const path = require("path");
const ResponseHelper = require("../ResponseHelper");
const {mkdir2} = require("../../tools");
const RecordInfoServer = require("../../servers/RecordInfo");


router.post("/", async (req, res, next) => {
    try {
        var params = req.body;
        if(!params.UUID){
            console.log('+++++++++++++++++++++++没有uuid');
            return
        }
        //var imgpath = `/home/cobot/ownuploads/${params.uuid}`;
        var imgpath = `C:\\ownnodeuploads\\${params.uuid}`
        var fileName = params.fileName.trim();
        console.log("+++++++++++++++++++++++fileName", fileName, fileName.length);
        await mkdir2(imgpath);
        var base64 = params.image.replace(/^data:image\/\w+;base64,/, ""); //去掉图片base64码前面部分data:image/png;base64
        var dataBuffer = new Buffer(base64, "base64"); //把base64码转成buffer对象，     var imgPathUrl = path.join(imgpath,`${fileName}.jpg`);
        var imgPathUrl = path.join(imgpath, `${fileName}.jpg`);
        console.log("+++++++++++++++++++++++imgPathUrl", imgPathUrl);
        fs.writeFile(imgPathUrl, dataBuffer, async function (err) {
            //用fs写入文件
            if (err) {
                console.log('+++++++++++++++++++++++err', err)
                ResponseHelper.sendErr(err, res);
            } else {
                const imgInfo = {

                    pid: params.uuid,
                    id:fileName +  parseInt(Math.random() * 1000000 + Math.random() * 1000000),
                    image: `http://${req.headers.host}/pubilc/uploads/${params.uuid}/${fileName}.jpg`
                }
                console.log('+++++++++++++++++++++++imgInfo', imgInfo);
                const record = await RecordInfoServer.getById(params.uuid);
                console.log('+++++++++++++++++++++++检查记录', record);
                const reportimg = record.reportimg;
                let reportimgVal;
                if (reportimg) {
                    reportimgVal = JSON.parse(reportimg);
                    reportimgVal.push(imgInfo);
                } else {
                    reportimgVal = [];
                    reportimgVal.push(imgInfo);
                }
                const updateReportimg = JSON.stringify(reportimgVal);
                const updateReportRes = await RecordInfoServer.update(params.uuid, {reportimg:updateReportimg});
                console.log('+++++++++++++++++++++++检查记录更新结果', updateReportRes);
                if (updateReportRes.length > 0) {
                    ResponseHelper.sendData(`http://${req.headers.host}/pubilc/uploads/${params.uuid}/${fileName}.jpg`, res);
                } else {
                    ResponseHelper.sendErr(`上传失败!`, res);
                }

            }
        });
    } catch (err) {
        console.log('+++++++++++++++++++++++err', err)
        ResponseHelper.sendErr(err, res);
    }
});



module.exports = router;